package com.gitee.fanx.jwt.core;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.gitee.fanx.jwt.config.JwtProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * jwt 工具包
 * @author fanx
 */
@Configuration
public class JwtCodec {
    private JwtProperties props;
    private Algorithm algorithm;
    private JWTVerifier verifier;
    private String issuer;

    public JwtCodec(JwtProperties props) {
        this.props = props;
        this.algorithm = Algorithm.HMAC256(props.getSecret());
        this.issuer = props.getIssuer();
        this.verifier = JWT.require(algorithm).withIssuer(issuer).build();
    }

    /**
     * 生成jwt
     * @param id
     * @return jwt-token
     */
    public String generate(Long id) {
        JWTCreator.Builder builder = JWT.create().withIssuer(issuer);
        builder.withClaim("id", id);
        Date current = new Date();
        builder.withIssuedAt(current);
        if (props.getExpire() != null) {
            long seconds = props.getExpire().getSeconds();
            Date expireTime = new Date(current.getTime() + seconds * 1000);
            builder.withExpiresAt(expireTime);
        }
        return builder.sign(algorithm);
    }

    /**
     * 解析jwt
     * @param token jwt-token
     * @return
     */
    public Long verify(String token) {
        return verifier.verify(token).getClaim("id").asLong();
    }
}
